package com.example.screenplayer;

import android.util.Log;
import android.view.Surface;

import com.gp.library.data.Constant;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class SocketClientManager implements ScreenSocketClient.SocketCallback {

  private ScreenDecoder mScreenDecoder;
  private ScreenSocketClient mSocketClient;
  private ScheduledExecutorService executor;
private ScheduledFuture<?> scheduledFuture;

public void start(Surface surface) {
    executor = Executors.newSingleThreadScheduledExecutor();
    mScreenDecoder = new ScreenDecoder();
    mScreenDecoder.startDecode(surface);
    try {
      // 需要修改为服务端的IP地址与端口
//      URI uri = new URI("ws://127.0.0.1:" + SOCKET_PORT);
      URI uri = new URI("ws://" + Constant.HOST + ":" + Constant.PORT);
      mSocketClient = new ScreenSocketClient(this, uri) {
          @Override
          public void onClose (int code, String reason, boolean remote) {
              super.onClose(code, reason, remote);
              scheduledFuture = executor.scheduleWithFixedDelay(connect, 2, 2, TimeUnit.SECONDS);
          }
      };
      executor.execute(connect);
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }
  }

  private Runnable connect = new Runnable() {
    @Override
    public void run () {
      Log.i("SocketClientManager", "delay connecting ....");
        if (mSocketClient != null) {
          if (!mSocketClient.getConnection().isOpen()) {
                mSocketClient.close();
                mSocketClient.connect();
          } else
            scheduledFuture.cancel(true);
        }
    }
  };

  public void stop() {
    if (mSocketClient != null) {
      mSocketClient.close();
    }
    if (mScreenDecoder != null) {
      mScreenDecoder.stopDecode();
    }
  }

  @Override
  public void onReceiveData(byte[] data) {
    if (mScreenDecoder != null) {
      mScreenDecoder.decodeData(data);
    }
  }
}
